package com.example.demo.ui.photo;

import android.net.Uri;
import android.os.Bundle;

import com.example.demo.bese.BaseActivity;
import com.example.demo.databinding.ActivityPhotoSelectorBinding;
import com.example.demo.task.PhotoChooserTask;
import com.example.demo.util.ToastUtil;
import com.orhanobut.logger.Logger;
import com.zhihu.matisse.Matisse;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: xtxiaolu
 * @date: 2023/7/12
 * 描述: 图片选择
 */
public class PhotoSelectorActivity extends BaseActivity {
    private ActivityPhotoSelectorBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPhotoSelectorBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.openSelectPhoto.setOnClickListener(v -> {
            PhotoChooserTask task = (PhotoChooserTask)getChooserTask(PhotoChooserTask.class);
            task.onCompleted(result -> {
                if (result.resultCode == RESULT_OK) {
                    List<Uri> selected = Matisse.obtainResult(result.data);
                    Logger.d("已选择图片数据：" + selected.toString());

                    initPhoto(selected);
                }
            }).show();
        });
    }

    private void initPhoto(List<Uri> listUri) {
        // 初始化SortablePhotoLayout
        binding.pictureRecyclerView.setEditable(true);

//        // 添加示例照片
        // 将List<Uri>转换为List<String>
        List<String> stringListUri = convertUriListToStringList(listUri);
        binding.pictureRecyclerView.setData(stringListUri);

        // 设置点击监听器（可选）
        binding.pictureRecyclerView.setOnItemClickListener((view, position) -> {
            ToastUtil.showShort("点击了第 " + position + " 张照片");
        });

        binding.pictureRecyclerView.setOnDeleteClickListener((view, position) -> {
//            binding.pictureRecyclerView.removePhoto(position);
            ToastUtil.showShort("删除了第 " + position + " 张照片");
        });
    }

    private List<String> convertUriListToStringList(List<Uri> uriList) {
        List<String> stringList = new ArrayList<>();
        for (Uri uri : uriList) {
            // 将Uri转换为字符串形式并添加到List<String>中
            stringList.add(uri.toString());
        }
        return stringList;
    }
}